import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import sharp from 'sharp';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';

export async function POST(request) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const formData = await request.formData();
    const file = formData.get('image');
    
    if (!file) {
      return NextResponse.json({ error: 'No file uploaded' }, { status: 400 });
    }

    // 将 File 对象转换为 Buffer
    const buffer = Buffer.from(await file.arrayBuffer());
    
    // 使用 sharp 压缩图片
    const compressedImageBuffer = await sharp(buffer)
      .resize(600, null, {
        withoutEnlargement: true,
        fit: 'inside'
      })
      .jpeg()
      .toBuffer();

    // 创建上传目录
    const uploadDir = join(process.cwd(), 'public', 'uploads');
    await mkdir(uploadDir, { recursive: true });

    // 生成文件名
    const fileName = `${Date.now()}.jpg`;
    const filePath = join(uploadDir, fileName);
    
    // 保存文件到本地
    await writeFile(filePath, compressedImageBuffer);
    
    // 返回文件的公共URL
    const publicUrl = `/uploads/${fileName}`;
    
    return NextResponse.json({ url: publicUrl });
  } catch (error) {
    console.error('Error uploading file:', error);
    return NextResponse.json({ error: 'Failed to upload file' }, { status: 500 });
  }
} 